<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use App\Models\User;
use Illuminate\Support\Str;
use App\Http\Responses\AjaxResult;
class LoginController extends Controller
{
    public function login(Request $request) {
        $validated = $request->validate([
            'username' => 'required|string',
            'password' => 'required|string',
            'code' => 'required|string',
            'uuid' => 'required|string',
        ]);

        // 验证验证码
        $captchaValid = captcha_check($validated['code'], $validated['uuid']);
        if (!$captchaValid) {
            return AjaxResult::error('验证码错误')->toResponse();
        }

        // 验证用户凭据
        if (Auth::attempt(['user_name' => $validated['username'], 'password' => $validated['password']])) {
            $user = Auth::user();
            // 生成自定义令牌
            $token = Str::random(60);
            // 存储token到Redis，设置过期时间为1小时
            Redis::set($token, $user->id, 'EX', 3600);
            Log::info('用户登录成功', ['user_name' => $validated['username']]);
            return response()->json([
                'code' => 200,
                'msg' => 'success',
                'token' => $token,
            ]);
        }

        // 记录登录失败日志
        Log::warning('登录失败: 用户名或密码错误', [
            'user_name' => $validated['user_name'],
            'ip' => $request->ip(),
            'user_agent' => $request->userAgent()
        ]);

        return AjaxResult::error('用户名或密码错误')->toResponse();
    }

    public function getInfo(Request $request) {
        $token = trim(str_replace('Bearer ', '', $request->header('Authorization') ?? $request->input('token')));
        if (!$token) {
            return AjaxResult::error('Token not provided')->toResponse();
        }

        $userId = Redis::get($token);
        if (!$userId) {
            return AjaxResult::error('Invalid or expired token')->toResponse();
        }

        $user = \App\Models\User::with('roles', 'dept')->find($userId);
        if (!$user) {
            return AjaxResult::error('User not found')->toResponse();
        }

        $data = [
            'code' => 200,
            'msg' => '操作成功',
            'permissions' => ['*:*:*'],
            'roles' => $user->roles->pluck('roleKey')->toArray(),
            'isDefaultModifyPwd' => false,
            'isPasswordExpired' => false,
            'user' => $user->toArray()
        ];

        return AjaxResult::success('操作成功', $data)->toResponse();
    }
}
